<template>
  <div class="app-container">
    <el-form ref="ruleForm" :rules="rules" :model="form" label-width="120px">
      <el-form-item label="单位名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item style="text-align: center;">
        <el-button :loading="buttonLoading" type="primary" @click="onSubmit('ruleForm')">确认</el-button>
        <el-button @click="onCancel">关闭</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  props: ['roleId'],
  data() {
    return {
      buttonLoading: false,
      form: {},
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleById();
  },
  methods: {
    getRoleById() {
      request({
        url: '/api/role/getRoleById',
        method: 'get',
        params: { id: this.roleId }
      }).then((res) => {
        this.form = res.result;
      }).catch(() => {

      })
    },
    onSubmit(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          request({
            url: '/api/role/updateRole',
            method: 'post',
            data: this.form
          }).then((res) => {
            this.buttonLoading = false;
            this.$message({
              message: res.resultCodeDesc
            })
            if (res.resultCode === '200') {
              this.$emit('refresh');
              this.$emit('closeDialog', false);
            }
          }).catch(() => {
            this.buttonLoading = false;
          })
        } else {
          this.$message({
            message: '表单验证失败',
            type: 'warning'
          })
          return false;
        }
      });
    },
    onCancel() {
      this.$emit('closeDialog', false);
    }
  }
}
</script>

<style scoped>

</style>
